package com.example.demo.service;

import com.example.demo.entity.PolicyInfo;
import com.example.demo.entity.TaskSupervisInfo;
import com.example.demo.entity.po.EsPolicyPO;
import com.example.demo.mapper.PolicyInfoMapper;
import com.example.demo.mapper.TaskSupervisInfoMapper;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.ArrayList;
import java.util.List;

/**
 * @author: Bin.L
 * @date: 2021/3/13 0013 12:31
 * @Description:
 */
@Service
@Slf4j
public class TaskSupervisInfoService {

    @Autowired
    TaskSupervisInfoMapper taskSupervisInfoMapper;

    @Resource
    PolicyInfoMapper policyInfoMapper;

    @Autowired
    ElasticSearchService elasticSearchService;

    public int saveTaskSupervisInfo(TaskSupervisInfo taskSupervisInfo) {
        return taskSupervisInfoMapper.insert(taskSupervisInfo);
    }

    /**
     * Mybatis plus 流式读取数据同步到ES
     */
    public void dataSynchronizeEs() {
        List<EsPolicyPO> listEs = new ArrayList<>(500);
        policyInfoMapper.readStreamingData(resultContext -> {
            // 取数据库查询对象
            PolicyInfo policyInfo = resultContext.getResultObject();

            // 转换ES存储对象
            EsPolicyPO esPolicyPO = new EsPolicyPO();
            esPolicyPO.setId(policyInfo.getId());
            esPolicyPO.setTitle(policyInfo.getTitle());
            esPolicyPO.setIssueDate(policyInfo.getIssueDate());
            esPolicyPO.setSourceType(policyInfo.getSourceType());
            esPolicyPO.setFile(new EsPolicyPO.File(policyInfo.getFileName(), policyInfo.getFileExt()));
            listEs.add(esPolicyPO);
            if (listEs.size() == 500) {
                // ES批量保存文档
                elasticSearchService.batchInsertDoc("policy", listEs);
                listEs.clear();
            }

        });
        log.info("最后保存的集合数据大小: {}条", listEs.size());
        elasticSearchService.batchInsertDoc("policy", listEs);
        listEs.clear();
    }
}
